package com.bwie.article.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bwie.article.config.KafkaConsumerConfig;
import com.bwie.article.mapper.ArticleMapper;
import com.bwie.article.service.ArticleService;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.Article;
import com.bwie.common.domain.Type;
import com.bwie.common.domain.User;
import com.bwie.common.result.Result;
import com.bwie.common.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.UUID;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private KafkaTemplate<Object,Object> kafkaTemplate;

    @Override
    public Result findArticleList() {
        List<Article> articleList = articleMapper.findArticleList();
        return Result.success(articleList);
    }

    @Override
    @Transactional
    public void addArticle(Article article) {
        String header = request.getHeader(TokenConstants.TOKEN);
        String userKey = JwtUtils.getUserKey(header);
        String userJSONStr = redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey);
        User user = JSONObject.parseObject(userJSONStr, User.class);
        article.setUserId(user.getUserId());
        add(article);
    }

    public void add(Article article){
        kafkaTemplate.send("aa", UUID.randomUUID().toString(),article);
    }

    @Override
    public Result findTypeList() {
        List<Type> typeList = articleMapper.findTypeList();
        return Result.success(typeList);
    }
}
